<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class ShopOrder extends Model
{
    protected $table = "shop_order";
    protected $fillable = [];

    protected $appends = ['order_status_name'];

    public function pay()
    {
        return $this->belongsTo(Pay::class);
    }

    public function detail()
    {
        return $this->belongsTo(ShopOrderDetail::class,'id','order_id');
    }

    public function getOrderStatusNameAttribute()
    {
        $name = '未知';
        switch($this->attributes['order_status']){
            case -1:
                $name = '已取消';
                break;
            case 0:
                $name = '待付款';
                break;
            case 1:
                $name = '待发货';
                break;
            case 2:
                $name = '待收货';
                break;
            case 3:
                $name = '已完成';
                break;
            case 4:
                $name = '已退款';
                break;
        }
        return $name;
    }

    //确认收货
    public static function shopOrderConfirmReceipt(){
        //扫描所以商品订单
        $shopOrder = ShopOrder::where("order_status",2)->get();
        if ($shopOrder->count()>0){
            foreach ($shopOrder as $item){
                //判断当前时间是否大于发货时间7天
                $cha = time()-7*24*60*60;
                if (strtotime($item['send_time'])<=$cha){
                    //自动确认收货
                    $item->order_status = 3;
                    $item->finished_time = Carbon::now();
                    $item->save();
                }
            }
        }
    }


}
